package com.gitee.feizns.webtemplate.commons.utils.encryption;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * 加密
 * @author feizns
 */
public abstract class EncryptUtils {

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static final char[] hexDigits = "0123456789abcdef".toCharArray();

    /**
     * sha_1加密
     * @param str
     * @return
     */
    public static String sha_1(String str) {
        return update(str, "SHA1");
    }

    /**
     * md5加密
     * @param str
     * @return
     */
    public static String md5(String str) {
        return update(str, "MD5");
    }

    private static String update(String str, String algorithm) {
        try {
            MessageDigest mdTemp = MessageDigest.getInstance(algorithm);
            mdTemp.update(str.getBytes(DEFAULT_CHARSET));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * https://blog.csdn.net/liaoxiaoyi121121/article/details/80408479
     * @param bytes
     * @return
     */
    private static String toHexString(byte[] bytes) {
        try ( Formatter formatter = new Formatter(); ) {
            for (byte b : bytes) {
                formatter.format("%02x", b);
            }
            return formatter.toString();
        }
    }

}
